import cv2  
import time
import easyocr
import numpy as np

# 裁剪
# 宽度是x 顶点向右方向  高度是y ,顶点向下方向
crop_x_min = 0   
crop_x_max = 1000
crop_y_min = 590   
crop_y_max = 1890

class frameClass:

    def ocr_test(self,img):
        ####设置识别中英文两种语言 need to run only once to load model into memory
        reader = easyocr.Reader(['en'], gpu = False,
                    download_enabled=False,
                    model_storage_directory='/home/cat/Src/model') 
        ress = reader.readtext(img)
        if ress:
            for res in ress:
                a = res[0][0]
                b = res[0][2]
                center_x = int((a[0]+b[0])/2)
                center_y = int((a[1]+b[1])/2)
                cv2.circle(self.frame, (center_x, center_y), 7, (125, 125, 0), -1)
                feature = [center_x,center_y,0]
                pts = [a,b]
                pts = np.array(pts,np.int32)
                cv2.rectangle(self.frame, pts[0],pts[1], (255, 0, 0), 3)  
                match res[1]:
                    case "A" | "4" | "^" | "Y":
                        self.position["A"] = feature
                    case "B" | "8":
                        self.position["B"] = feature
                    case "C":
                        self.position["C"] = feature
                    case "D" | "0" | "O" | "o":
                        self.position["D"] = feature                           
                print("recongnitioin Character is : %s" %res[1])

    
    def run(self,):
        #### 通过CV库函数获取视频流数据
        cap = cv2.VideoCapture(9,)
        cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))  

        while True:  
            ret, self.frame = cap.read()  
            if not ret:
                time.sleep(0.1)
                #### 图像一旦获取失败，不断循环获取图像
                cap = cv2.VideoCapture(9,)
                cap.set(cv2.CAP_PROP_FOURCC,cv2.VideoWriter_fourcc('M','J','P','G'))  
                print("Can't to capture from camera. Exiting ...")  
                break  
            
            #### 图像裁剪--感兴趣区域进行检测
            crop = np.zeros([1944,2592,3],np.uint8)
            crop[crop_x_min:crop_x_max,crop_y_min:crop_y_max] = self.frame[crop_x_min:crop_x_max,crop_y_min:crop_y_max]
            img = crop
            
            #### 二维码检测
            self.QR_test(img)
            time.sleep(0.01)
            
            #### 图像显示与保存
            cv2.imshow('frame', self.frame)
            cv2.imwrite(f"crop.png",img)
            cv2.imwrite(f"frame.png",self.frame)
        
            # 按下'q'键退出循环  
            if cv2.waitKey(1) & 0xFF == ord('q'):  
                break  

        # 释放摄像头资源  
        cap.release()  
        # 关闭所有OpenCV窗口  
        cv2.destroyAllWindows()

a = frameClass()
a.run()